import { defineStore } from 'pinia'
import { store } from '../index'
import { parse, stringify } from 'zipson'
import {
  TypingContentTypeEnum,
  TypingDurationEnum,
  TypingModeEnum
} from '@renderer/enums/TypingEnum'
import { chineseSentences, chineseWords } from '@renderer/mock/ChineseText'
import { pinyin } from 'pinyin-pro'
import { shuffleArray } from '@renderer/utils'
import { englishSentences, englishWords } from '@renderer/mock/EnglishText'

interface TypingState {
  // 当前打字模式（中文/英文）
  mode: TypingModeEnum
  // 用户自定义的文本内容
  customText: string
  // 内容类型
  contentType: TypingContentTypeEnum
  // 测试时长（15s/30s/60s/90s）
  duration: TypingDurationEnum
  // 自定义测试时长（单位：秒）
  customDuration: number
  // 是否正在录制
  isRecording: boolean
  // 当前输入字符的索引位置
  currentIndex: number
  // 计时器是否正在运行
  isTimerRunning: boolean
  // 倒计时时间（单位：秒）
  countdown: number
  // 当前测试的文本内容
  typingText: string
  // 当前测试的词语列表
  words: string[]
  // 当前测试的句子列表
  sentences: string[]
  // 总错误字符数
  totalErrorChars: number
  // 总输入字符数
  totalTypedChars: number
  // 总字符数
  totalCharCount: number
  // 正确输入字符数
  correctChars: number
  // 是否暂停
  isPaused: boolean
  // 当前输入的词语列表
  inputs: string[]
  // 测试是否完成
  isCompleted: boolean
  // 实际使用时间（秒）
  actualTime: number
  // 计时器
  timer: any
  // 每秒WPM记录
  wpmHistory: number[]
  // 每秒错误次数记录
  errorHistory: number[]
  // 上一秒的错误总数（用于计算每秒新增错误数）
  lastErrorCount: number
  // 输入错误的总次数（包括已修正的错误）
  totalErrorCount: number
}

const getWords = (mode: TypingModeEnum) => {
  let words: string[] = []
  if (mode === TypingModeEnum.CHINESE) {
    words = shuffleArray(chineseWords)
  } else {
    words = shuffleArray(englishWords)
  }
  let totalCharCount = 0
  for (const word of words) {
    const pinyinText = pinyin(word, { toneType: 'none' }).replace(/\s/g, '')
    totalCharCount += pinyinText.length
  }
  return {
    words,
    totalCharCount
  }
}

const getSentences = (mode: TypingModeEnum) => {
  const sentences = mode === TypingModeEnum.CHINESE ? chineseSentences : englishSentences
  return shuffleArray(sentences)
}

export const useTypingStore = defineStore('TypingStore', {
  state: (): TypingState => ({
    mode: TypingModeEnum.CHINESE,
    customText: '',
    contentType: TypingContentTypeEnum.WORD,
    duration: TypingDurationEnum.TIME_15,
    customDuration: 0,
    isRecording: false,
    currentIndex: 0,
    isTimerRunning: false,
    countdown: Number(TypingDurationEnum.TIME_15),
    typingText: '开始输入以测试您的打字速度和准确度。',
    totalTypedChars: 0,
    correctChars: 0,
    isPaused: false,
    words: [],
    sentences: [],
    totalCharCount: 0,
    totalErrorChars: 0,
    inputs: [],
    isCompleted: false,
    actualTime: 0,
    timer: null,
    wpmHistory: [],
    errorHistory: [],
    lastErrorCount: 0,
    totalErrorCount: 0
  }),
  getters: {
    formatTime: (state) => {
      // 如果时间到了且测试仍在进行，立即标记为完成
      if (state.countdown === 0 && !state.isCompleted && state.isTimerRunning && !state.isPaused) {
        // 直接调用completed完成测试
        useTypingStore().completed()
      }
      const minutes = Math.floor(state.countdown / 60)
      const seconds = state.countdown % 60
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    wpm: (state) => {
      if (state.actualTime === 0) return 0

      // 每5个字符算一个单词（国际标准）
      // 但只计算正确输入的字符，忽略错误的字符
      const totalTyped = state.totalTypedChars // 总输入字符数
      const correctChars = totalTyped > 0 ? Math.max(0, totalTyped - state.totalErrorChars) : 0

      // 时间转换为分钟
      const minutes = state.actualTime / 60

      // 正确字符数除以5，再除以时间（分钟）
      return Math.round(correctChars / 5 / minutes)
    },
    maxWpm: (state) => {
      if (state.wpmHistory.length === 0) return 0
      return Math.max(...state.wpmHistory)
    },
    accuracy: (state) => {
      if (state.totalTypedChars === 0) return 100
      return Math.round(
        ((state.totalTypedChars - state.totalErrorChars) / state.totalTypedChars) * 100
      )
    },
    averageWpm: (state) => {
      if (state.wpmHistory.length === 0) return 0
      return Math.round(
        state.wpmHistory.reduce((sum, wpm) => sum + wpm, 0) / state.wpmHistory.length
      )
    },
    isStart: (state) => {
      return state.isTimerRunning && !state.isPaused
    }
  },
  actions: {
    // 设置打字模式
    setMode(mode: TypingModeEnum) {
      this.mode = mode
    },

    // 设置测试时长
    setDuration(duration: TypingDurationEnum) {
      this.duration = duration
      if (duration === TypingDurationEnum.CUSTOM) {
        this.countdown = this.customDuration
      } else {
        this.countdown = duration
      }
    },

    // 设置内容类型
    setContentType(contentType: TypingContentTypeEnum) {
      this.contentType = contentType
    },

    // 设置自定义测试时长
    setCustomDuration(duration: number) {
      this.customDuration = duration
      this.duration = TypingDurationEnum.CUSTOM
      this.countdown = duration
    },

    // 设置用户自定义的文本内容
    setCustomText(text: string) {
      this.customText = text
      this.contentType = TypingContentTypeEnum.CUSTOM
    },

    // 设置当前测试的文本内容
    setTypingText(text: string) {
      this.typingText = text
    },

    // 设置是否正在录制
    toggleRecording() {
      this.isRecording = !this.isRecording
    },

    // 增加输入错误字符数
    incrementErrorChars() {
      this.totalErrorChars++
    },

    // 增加总错误次数（包括已修正的错误）
    incrementTotalErrorCount() {
      this.totalErrorCount++
    },

    // 重置测试
    resetTyping() {
      this.currentIndex = 0
      this.totalErrorChars = 0
      this.totalTypedChars = 0
      this.correctChars = 0
      this.isTimerRunning = false
      this.isCompleted = false
      this.actualTime = 0
      this.totalErrorCount = 0
      this.wpmHistory = []
      this.errorHistory = []
      this.lastErrorCount = 0
      this.initCountdown()
      this.isPaused = false
      if (this.contentType === TypingContentTypeEnum.SENTENCE) {
        this.initSentences()
      } else {
        this.initWords()
      }
    },

    // 重新开始测试
    redoTyping() {
      this.currentIndex = 0
      this.totalErrorChars = 0
      this.totalTypedChars = 0
      this.correctChars = 0
      this.isTimerRunning = false
      this.isCompleted = false
      this.actualTime = 0
      this.totalErrorCount = 0
      this.wpmHistory = []
      this.errorHistory = []
      this.lastErrorCount = 0
      this.initCountdown()
      this.isPaused = false
      if (this.contentType === TypingContentTypeEnum.SENTENCE) {
        this.inputs = Array(this.sentences.length).fill('')
      } else {
        this.inputs = Array(this.words.length).fill('')
      }
    },

    // 暂停打字
    pauseTyping() {
      this.isPaused = true
      this.stopTimer()
    },

    // 恢复打字
    resumeTyping() {
      this.isPaused = false
      this.startTimer()
    },

    // 开始计时
    startTimer() {
      if (this.isTimerRunning) return

      this.isTimerRunning = true
      this.timer = setInterval(() => {
        if (this.isPaused) return

        this.actualTime++
        this.countdown--

        // 记录当前WPM
        const currentWpm = this.calculateCurrentWpm()
        this.wpmHistory.push(currentWpm)

        // 记录当前错误数
        const currentErrorCount = this.totalErrorCount
        const newErrors = currentErrorCount - this.lastErrorCount
        this.errorHistory.push(newErrors)
        this.lastErrorCount = currentErrorCount

        // 如果时间到了，完成测试
        if (this.countdown === 0) {
          this.completed()
        }
      }, 1000)
    },

    // 计算当前WPM
    calculateCurrentWpm() {
      if (this.actualTime === 0) return 0

      // 每5个字符算一个单词（国际标准）
      const correctChars =
        this.totalTypedChars > 0 ? Math.max(0, this.totalTypedChars - this.totalErrorChars) : 0

      // 时间转换为分钟
      const minutes = this.actualTime / 60

      // 正确字符数除以5，再除以时间（分钟）
      return Math.round(correctChars / 5 / minutes)
    },

    // 停止计时
    stopTimer() {
      this.isTimerRunning = false
      clearInterval(this.timer)
    },

    // 完成打字
    completed() {
      if (this.isCompleted) return

      this.isPaused = false
      this.isCompleted = true
      this.initCountdown()
      this.stopTimer()
    },

    initCountdown() {
      if (this.duration === TypingDurationEnum.CUSTOM) {
        this.countdown = this.customDuration
      } else {
        this.countdown = this.duration
      }
    },

    // 初始化词语列表
    initWords() {
      const { words, totalCharCount } = getWords(this.mode)
      this.words = words
      this.totalCharCount = totalCharCount
      this.inputs = Array(this.words.length).fill('')
    },

    // 初始化句子列表
    initSentences() {
      const sentences = getSentences(this.mode)
      this.sentences = sentences
      this.totalCharCount = sentences.join('').length
      this.inputs = Array(this.sentences.length).fill('')
    }
  },
  persist: {
    key: 'typing',
    storage: localStorage,
    pick: [
      'mode',
      'contentType',
      'duration',
      'customDuration',
      'countdown',
      'customText',
      'typingText'
    ],
    serializer: {
      deserialize: parse,
      serialize: stringify
    }
  }
})

// 非setup
export function useTypingStoreHook() {
  return useTypingStore(store)
}
